import 'package:flutter/cupertino.dart';
import 'package:love_app/config/prefs.dart';
import 'package:love_app/enum/bind_lover.dart';
import 'package:love_app/enum/login_status.dart';
import 'package:love_app/enum/sex.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/model/user_info_model.dart';
import 'package:love_app/service/form_token_api.dart';
import 'package:love_app/service/user_info_api.dart';
import 'package:love_app/service/verify_token.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

// app启动初数据始化
class MainInit {
  static Future<LoginStatus> getLoginStatus({BuildContext context}) async {
    // 返回一个ShareProvider，里面保存一些全局的共享数据
    return await SharedPreferences.getInstance().then((prefs) async {
      String tokenData = prefs.get(Prefs.token);
      if (tokenData == null) {
        return LoginStatus.noLogin;
      } else {
        bool verfyToken = await VerifyToekn().verfyToken(tokenData);
        if (verfyToken == true) {
          // return ShareProvider();
          UserInfoModel userInfoModel =
              await UserInfoApi().getUserInfo(tokenData);
          Sex userSex = IntToSex.getSex(userInfoModel.data.myInfo.sex);
          BindLover bindLover = IntToBindLover.getBindLover(userInfoModel.data.bindLover);
          int uid = userInfoModel.data.myInfo.uid;
          String nickname = userInfoModel.data.myInfo.nickname;
          String phone = userInfoModel.data.myInfo.phone;
          String headerImage = userInfoModel.data.myInfo.headimg;
          String formToken = await FormTokenApi().getFormToken(tokenData);
          final ShareProvider shareProvider = Provider.of<ShareProvider>(context, listen: false);
          shareProvider.loginInit(tokenData, userSex, LoginStatus.login, uid, formToken, bindLover,
          userInfoModel.data.loverInfo, nickname, phone, headerImage);
          return LoginStatus.login;
        }
        return LoginStatus.noLogin;
      }
    });
  }
}
